package com.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.item.dao.UserMapper;
import com.item.entity.WxUser;
import com.item.entity.dto.LayuiListPage;
import com.item.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhang-rongyao
 * @since 2021-07-20
 */
@Service
@CacheConfig(cacheNames = "user")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, WxUser> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    @CachePut(key = "#wxUser.id")
    public Integer addUser(WxUser wxUser) {
        int insert = userMapper.insert(wxUser);
        log.info("存入数据库【User】= {}", wxUser);
        return insert;
    }

    @Override
    //@Cacheable(key = "#id",unless = "#result == null ")
    public WxUser getUser(Integer id) {
        WxUser wxUser = userMapper.selectById(id);
        log.info("从数据库获取【User】= {}", wxUser);
        return wxUser;
    }

    @Override
    @Cacheable(key = "#id",unless = "#result == null ")
    public void delUser(Integer id) {
        userMapper.deleteById(id);
        log.info("从数据库删除【User】");
    }

    @Override
    public Integer updateUser(WxUser wxUser) {
        UpdateWrapper<WxUser> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", wxUser.getId());
        int i = userMapper.update(wxUser,wrapper);
        return i;
    }

    @Override
    public LayuiListPage<WxUser> getAllUsers(Integer page, Integer limit) {

        Page<List<WxUser>> dataPage = new Page<>(page,limit);
        List<WxUser> userList = userMapper.getUserPage(dataPage);

        LayuiListPage listPage = new LayuiListPage<>();

        if (userList == null || userList.size() == 0) {
            listPage.setCode(1);
            listPage.setMsg("未查询到结果数据");
            listPage.setCount(0);
            return listPage;
        } else {
            listPage.setCode(0);
            listPage.setCount(dataPage.getTotal());
            listPage.setData(userList);
            return listPage;
        }
    }
}
